package hlhj.fhp.supreme

import android.Manifest
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.widget.TextView
import com.bumptech.glide.Glide
import com.gyf.barlibrary.ImmersionBar
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.customview.ChangeAddressPopwindow
import hlhj.fhp.supreme.customview.GroupPayDialog
import hlhj.fhp.supreme.fragment.*
import hlhj.fhp.supreme.javabean.*
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import hlhj.fhp.supreme.utils.SPHelper
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.util.ArrayList

//13540738350
class MainActivity : BaseAty() {

    private var homeFgm:Fragment?=null
    private var selfFgm:SelfFgm?=null
    private var tipsFgm:Fragment?=null
    private var actFgm:Fragment?=null
    private var serveFgm :Fragment?=null
    private var isExit=false
    override fun getContentId(): Int = R.layout.activity_main
    companion object {
        open var isHxOk=false;
    }
    override fun initView() {
        LogUtil.logi(MyUtils.getMD5("123456"))
        LogUtil.e("fhpp","------------------------------")
        getUserInfo()
        saveQNToken()
        homeFgm=HomeFgm()
        LogUtil.e("fhpp","------------------------------")
        selfFgm= SelfFgm()
        tipsFgm=TipsFgm()
        actFgm=ActFgm()
        serveFgm=ServeFgm()
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.rp,homeFgm)
        transaction.add(R.id.rp,selfFgm)
        transaction.add(R.id.rp,tipsFgm)
        transaction.add(R.id.rp,actFgm)
        transaction.add(R.id.rp,serveFgm)
        transaction.hide(homeFgm)
        transaction.hide(selfFgm)
        transaction.hide(tipsFgm)
        transaction.hide(actFgm)
        transaction.hide(serveFgm)
        transaction.commit()
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                ||ActivityCompat.checkSelfPermission(this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED
                ||ActivityCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO)!=PackageManager.PERMISSION_GRANTED) run {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.RECORD_AUDIO), 0)
        }
        getGroupMoney()
        getUnPayGroup()
        getTextUn()
//        setMarq()
    }

    private fun getTextUn() {
        OkGo.post<MessageListBean>(Urls.BaseUrl+Urls.MESSAGE_LIST)
                .execute(object :JsonCallBack<MessageListBean>(this){
                    override fun onSuccess(response: Response<MessageListBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            EventBus.getDefault().postSticky(PreEvent())
                            for (i in 0..bean?.data.size-1){
                                if (bean?.data[i].status==0){
                                    EventBus.getDefault().postSticky(RefreshEvent(0))
//
                                }
                            }
                        }else{
                        }
                    }
                })
    }

    private fun getGroupMoney() {
        OkGo.post<PhoneBean>(Urls.BaseUrl+Urls.PHONE)
                .params("type","breakup")
                .execute(object :JsonCallBack<PhoneBean>(this){
                    override fun onSuccess(response: Response<PhoneBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            Contents.ONE=bean?.data.breakup
                        }
                    }
                })
        OkGo.post<PhoneBean>(Urls.BaseUrl+Urls.PHONE)
                .params("type","five_breakup")
                .execute(object :JsonCallBack<PhoneBean>(this){
                    override fun onSuccess(response: Response<PhoneBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            Contents.FIVE=bean?.data!!.five_breakup
                        }
                    }
                })
        OkGo.post<PhoneBean>(Urls.BaseUrl+Urls.PHONE)
                .params("type","ten_breakup")
                .execute(object :JsonCallBack<PhoneBean>(this){
                    override fun onSuccess(response: Response<PhoneBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            Contents.TEN=bean?.data.ten_breakup
                        }
                    }
                })
    }

    private fun getUnPayGroup() {
        OkGo.post<UnPayBean>(Urls.BaseUrl+Urls.UNPAY_GROUP)
                .execute(object :JsonCallBack<UnPayBean>(this){
                    override fun onSuccess(response: Response<UnPayBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            if (bean?.data!=null){
                                if (bean?.data.size>0){
                                    GroupPayDialog(this@MainActivity,bean?.data as ArrayList<UnPayBean.DataBean>).show()

                                }
                            }
                        }
                    }
                })
    }

    private fun saveQNToken() {
    }
    private fun getUserInfo() {
        LogUtil.log("紧着方法？")
        OkGo.post<UserInfoBean>(Urls.BaseUrl+Urls.UserInfo)
                .execute(object :JsonCallBack<UserInfoBean>(this){
                    override fun onError(response: Response<UserInfoBean>?) {
                        super.onError(response)
                        LogUtil.log(response?.message()!!)
                    }
                    override fun onSuccess(response: Response<UserInfoBean>?) {
                        val bean = response?.body()
                        LogUtil.log("紧着方法？${bean?.code}")
                        if (bean?.code==1){
                            SPHelper.saveUser(this@MainActivity,bean.data)
                            LogUtil.log("环信登录开始${bean?.data.hx_user_name}${bean?.data.hx_user_pass}")
                            EMClient.getInstance().login(bean?.data.hx_user_name.toString(),bean?.data.hx_user_pass,object : EMCallBack {
                                override fun onSuccess() {
                                    isHxOk=true
//                                    EventBus.getDefault().post(HxOkEvent())
                                    LogUtil.log("环信登录成功")
                                }

                                override fun onProgress(progress: Int, status: String?) {
                                }

                                override fun onError(code: Int, error: String?) {
                                    LogUtil.log("环信登录失败${error}")
                                }
                            })
                        }
                    }
                })
    }

    override fun initListener() {
        bottomBar.setOnCheckedChangeListener { group, checkedId ->
            LogUtil.log("选择Id$checkedId")
            when(checkedId){
                R.id.rbHome->{
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(homeFgm)
                    transaction.hide(selfFgm)
                    transaction.hide(actFgm)
                    transaction.hide(tipsFgm)
                    transaction.hide(serveFgm)
                    transaction.commit()
                }
                R.id.rbTips->{
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(tipsFgm)
                    transaction.hide(homeFgm)
                    transaction.hide(selfFgm)
                    transaction.hide(actFgm)
                    transaction.hide(serveFgm)

                    transaction.commit()
                }
                R.id.rbAct->{
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(actFgm)
                    transaction.hide(homeFgm)
                    transaction.hide(selfFgm)
                    transaction.hide(tipsFgm)
                    transaction.hide(serveFgm)

                    transaction.commit()
                }
                R.id.rbServe->{
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(serveFgm)
                    transaction.hide(homeFgm)
                    transaction.hide(selfFgm)
                    transaction.hide(tipsFgm)
                    transaction.hide(actFgm)
                    transaction.commit()
                }
                R.id.rbSelf->{
                    val transaction = supportFragmentManager.beginTransaction()
                    transaction.show(selfFgm)
                    transaction.hide(homeFgm)
                    transaction.hide(tipsFgm)
                    transaction.hide(actFgm)
                    transaction.hide(serveFgm)
                    transaction.commit()
                }
            }
        }
        bottomBar.check(R.id.rbHome)

    }

    override fun onResume() {
        super.onResume()
        EventBus.getDefault().postSticky(RefreshFgmEvent())
    }
    override fun onBackPressed() {

        if (isExit){
            MyUtils.AtyContainer.getInstance().finishAllActivity()
        }else{
            isExit=true
            MyUtils.toast("再按返回键退出App")
            Thread(Runnable {
                Thread.sleep(2000)
                isExit=false
            }).start()
        }
    }
}
